package com.infoland.modules.standardDynamic.service.impl;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.commons.io.IOUtils;

import com.infoland.common.util.CniswsUtil;
import com.infoland.modules.basic.Message;
import com.infoland.modules.basic.SystemConfiguration;
import com.infoland.modules.members.model.UserInfo;
import com.infoland.modules.standardDynamic.service.StandardDynamicService;
import com.jfinal.kit.Base64Kit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import ws.client.WebApi;

/**
 * @Description
 * @author Wsy
 * @date 2017年7月27日 下午3:59:02
 * @version V1.3.1
 */

public class StandardDynamicServiceImpl implements StandardDynamicService {

	/**
	 * 
	 * Description 根据标准状态获取标准信息
	 * 
	 * @param standardType
	 *            标准状态
	 * @return 标准分页对象
	 */
	@Override
	public Message getStandardAvisoByType(String standardType, String pageNumber) {
		// 实例化Message对象
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		// 实例化连接配置对象
		WebApi api = new WebApi();
		// 调用中标院接口
		String[] params = new String[] { "orgLoginName", "password", "ukeyId", "orgCode", "type", "iPageIndex",
				"iPageSize" };
		String[] paramsValue = new String[] { CniswsUtil.getUserName(), CniswsUtil.getPassword(), "", "", standardType,
				pageNumber, CniswsUtil.getPageSize() };
		OMElement qs = null;
		try {
			qs = api.callMethod(CniswsUtil.getWsdl(), CniswsUtil.getNameSpace(), "getStandardAvisoByType", params,
					paramsValue);
		} catch (AxisFault e) {
			message.setMessage("查询失败，请重试！");
			return message;
		}
		Page<Map<String, Object>> pagelist = new Page<Map<String, Object>>();
		List<Map<String, Object>> list = api.getNodeList(qs);
		if (list != null) {
			for(int i=0;i<list.size();i++){
				Map<String, Object> map = list.get(i);
				String strDate = (String) map.get("a101");
				String reStr = reDate(strDate);
				map.put("a101", reStr);
			}
			// 重置list分页信息返回前台
			@SuppressWarnings("unchecked")
			Map<String, Object> map = (Map<String, Object>) list.get(0).get("pagination");
			Integer pageNum = Integer.parseInt((String) map.get("pageNo"));
			Integer pageSize = Integer.parseInt((String) map.get("pageSize"));
			Integer pageCount = Integer.parseInt((String) map.get("totalPageNum"));
			Integer pageRow = Integer.parseInt((String) map.get("recTotal"));
			//限制页面显示数据数量，设置为最多30页，450条
			if (pageCount >= 30) {
				pageCount = 30;
			}
			if (pageRow >= 450) {
				pageRow = 450;
			}
			pagelist = new Page<Map<String, Object>>(list, pageNum, pageSize, pageCount, pageRow);
			message.setMessage("查询成功！");
			message.setSuccess(Boolean.TRUE);
			message.setObject(pagelist);
		} else {
			message.setMessage("此栏目暂时没有数据！");
		}
		return message;
	}
	
	/**
	 * 
	 * @Description 	处理中标院返回的字符串类型date
	 * @author Wsy
	 * @param strDate	中标院返回的字符串date
	 * @return			字符串
	 * 
	 */
	public String reDate(String strDate) {
		String reStr = "";
		if(strDate.indexOf("年") > 0){
			strDate = strDate.replace("年", "-").replace("月", "-").replace("日", "");
			for (int j = 0; j < strDate.length(); j++) {
				char str;
				switch (strDate.charAt(j)) {
				case '〇':
					str = '0';
					break;
				case '一':
					str = '1';
					break;
				case '二':
					str = '2';
					break;
				case '三':
					str = '3';
					break;
				case '四':
					str = '4';
					break;
				case '五':
					str = '5';
					break;
				case '六':
					str = '6';
					break;
				case '七':
					str = '7';
					break;
				case '八':
					str = '8';
					break;
				case '九':
					str = '9';
					break;
				default:
					str = strDate.charAt(j);
				}
				strDate = strDate.replace(strDate.charAt(j), str);
			}
			String[] strs = strDate.split("-");
			if (strs[1].length() == 2) {
				strs[1] = strs[1].replace("十", "1");
			} else {
				if (strs[1].indexOf("十") >= 0) {
					strs[1] = strs[1].replace("十", "10");
				} else {
					strs[1] = "0".concat(strs[1]);
				}
			}
			if (strs[2].length() == 3) {
				strs[2] = strs[2].replace("十", "");
			} else if (strs[2].length() == 1) {
				if (strs[2].indexOf("十") >= 0) {
					strs[2] = "10";
				} else {
					strs[2] = "0".concat(strs[2]);
				}
			} else if (strs[2].length() == 2) {
				if (strs[2].indexOf("十") == 0) {
					strs[2] = strs[2].replace("十", "1");
				} else if (strs[2].indexOf("十") == 1) {
					strs[2] = strs[2].replace("十", "0");
				}
			}
			reStr = strs[0].concat("-").concat(strs[1]).concat("-").concat(strs[2]);
		} else {
			reStr = strDate;
		}
		return reStr;
	}

	/**
	 * 
	 * Description 根据标识符获取标准动态详细信息
	 * 
	 * @param id
	 *            标识符
	 * @return
	 */
	@Override
	public Message getStandardInfoById(String id) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		WebApi a = new WebApi();
		OMElement o = null;
		String[] params = new String[] { "orgLoginName", "password", "ukeyId", "orgCode", "A001" };
		String[] paramsValue = new String[] { CniswsUtil.getUserName(), CniswsUtil.getPassword(), "", "", id };
		try {
			o = a.callMethod(CniswsUtil.getWsdl(), CniswsUtil.getNameSpace(), "getStandardDetail", params, paramsValue);
		} catch (AxisFault e) {
			e.printStackTrace();
			message.setMessage("出现异常,请联系管理员");
		}
		if (o != null) {
			Map<String, Object> map = a.getReturn(o);
			message.setObject(map.get("return"));
			System.out.println(map.get("return"));
			message.setMessage("获取详情成功");
			message.setSuccess(Boolean.TRUE);
		} else {
			message.setMessage("获取详情失败,请联系管理员");
		}
		return message;
	}

	/**
	 * 
	 * @Description 根据标识符（A001）获得代替/被代替关系，展示代替/被代替关系的详细信息。
	 * @author yinyg
	 * @param id
	 *            标识符
	 * @param type
	 *            需要查询的信息类型代替（A461）/被代替（A462）
	 * @return
	 */
	@Override
	public Message getReplaceORBereplaceStandard(String id, String type) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		// 实例化连接配置对象
		WebApi api = new WebApi();
		// 调用中标院接口
		String[] params = new String[] { "orgLoginName", "password", "ukeyId", "orgCode", "A001", "type" };
		String[] paramsValue = new String[] { CniswsUtil.getUserName(), CniswsUtil.getPassword(), "",
				CniswsUtil.getOrgCode(), id, type };
		OMElement qs = null;
		try {
			qs = api.callMethod(CniswsUtil.getWsdl(), CniswsUtil.getNameSpace(), "getReplaceORBereplaceStandard",
					params, paramsValue);
		} catch (AxisFault e) {
			e.printStackTrace();
			message.setMessage("链接失败，请重试！");
			return message;
		}
		List<Map<String, Object>> list = api.getNodeList(qs);
		List<Map<String, Object>> listNew = new ArrayList<Map<String, Object>>();
		if (list.size() > 0 && list.get(0) != null) {
			for (Map<String, Object> standardWrap : list) {
				Map<String, Object> standardWrapNew = new HashMap<String, Object>();
				listNew.add(standardWrapNew);
				standardWrapNew.put("recordState", standardWrap.get("a000"));
				standardWrapNew.put("recordStateInt", standardWrap.get("a001"));
				standardWrapNew.put("standardNo", standardWrap.get("a100"));
				standardWrapNew.put("standardName", standardWrap.get("a298"));
				standardWrapNew.put("standardEngName", standardWrap.get("a302"));
			}
			message.setObject(listNew);
			message.setMessage("查询成功！");
			message.setSuccess(Boolean.TRUE);
		} else {
			message.setMessage("获取失败");
		}
		return message;
	}

	/**
	 * 
	 * @Description 根据标识符（A001）获得引用/被引用关系，展示引用/被引用关系的详细信息。
	 * @author yinyg
	 * @param id
	 *            标识符
	 * @param type
	 *            需要查询的信息类型引用（A502）/被引用（An502）
	 * @return
	 */
	@Override
	public Message getQuoteORQuotedStandard(String id, String type) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		// 实例化连接配置对象
		WebApi api = new WebApi();
		// 调用中标院接口
		String[] params = new String[] { "orgLoginName", "password", "ukeyId", "orgCode", "A001", "type" };
		String[] paramsValue = new String[] { CniswsUtil.getUserName(), CniswsUtil.getPassword(), "",
				CniswsUtil.getOrgCode(), id, type };
		OMElement qs = null;
		try {
			qs = api.callMethod(CniswsUtil.getWsdl(), CniswsUtil.getNameSpace(), "getQuoteORQuotedStandard", params,
					paramsValue);
		} catch (AxisFault e) {
			e.printStackTrace();
			message.setMessage("链接失败，请重试！");
			return message;
		}
		List<Map<String, Object>> list = api.getNodeList(qs);
		List<Map<String, Object>> listNew = new ArrayList<Map<String, Object>>();
		if (list.size() > 0 && list.get(0) != null) {
			for (Map<String, Object> standardWrap : list) {
				Map<String, Object> standardWrapNew = new HashMap<String, Object>();
				listNew.add(standardWrapNew);
				standardWrapNew.put("recordState", standardWrap.get("a000"));
				standardWrapNew.put("recordStateInt", standardWrap.get("a001"));
				standardWrapNew.put("standardNo", standardWrap.get("a100"));
				standardWrapNew.put("standardName", standardWrap.get("a298"));
				standardWrapNew.put("standardEngName", standardWrap.get("a302"));
			}
			message.setObject(listNew);
			message.setMessage("查询成功！");
			message.setSuccess(Boolean.TRUE);
		} else {
			message.setMessage("获取失败");
		}
		return message;
	}

	/**
	 * 
	 * @Description 根据标识符（A001）获得采用/被采用关系，展示采用/被采用关系的详细信息。
	 * @author yinyg
	 * @param id
	 *            标识符
	 * @param type
	 *            需要查询的信息类型采用（A800）/被采用（An800）
	 * @return
	 */
	@Override
	public Message getAdoptORAdoptedStandard(String id, String type) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		// 实例化连接配置对象
		WebApi api = new WebApi();
		// 调用中标院接口
		String[] params = new String[] { "orgLoginName", "password", "ukeyId", "orgCode", "A001", "type" };
		String[] paramsValue = new String[] { CniswsUtil.getUserName(), CniswsUtil.getPassword(), "",
				CniswsUtil.getOrgCode(), id, type };
		OMElement qs = null;
		try {
			qs = api.callMethod(CniswsUtil.getWsdl(), CniswsUtil.getNameSpace(), "getAdoptORAdoptedStandard", params,
					paramsValue);
		} catch (AxisFault e) {
			e.printStackTrace();
			message.setMessage("链接失败，请重试！");
			return message;
		}
		List<Map<String, Object>> list = api.getNodeList(qs);
		List<Map<String, Object>> listNew = new ArrayList<Map<String, Object>>();
		if (list.size() > 0 && list.get(0) != null) {
			for (Map<String, Object> standardWrap : list) {
				Map<String, Object> standardWrapNew = new HashMap<String, Object>();
				listNew.add(standardWrapNew);
				standardWrapNew.put("recordState", standardWrap.get("a000"));
				standardWrapNew.put("recordStateInt", standardWrap.get("a001"));
				standardWrapNew.put("standardNo", standardWrap.get("a100"));
				standardWrapNew.put("standardName", standardWrap.get("a298"));
				standardWrapNew.put("standardEngName", standardWrap.get("a302"));
			}
			message.setObject(listNew);
			message.setMessage("查询成功！");
			message.setSuccess(Boolean.TRUE);
		} else {
			message.setMessage("获取失败");
		}
		return message;
	}

	/**
	 * 
	 * @Description 根据标识符（A001）获得同一中国/国际标准分类下的题录信息，展示同一中国/国际标准分类下的题录信息。
	 * @author yinyg
	 * @param type
	 *            需要查询的信息类型中标（Ccs）/国标（Ics）
	 * @param code
	 *            当type是中标（Ccs）时，code是中标的值（A825）,当type是国标（Ics）时，code是国标的值（A826）
	 * @return
	 */
	@Override
	public Message getCcsOrIcsStandard(String type, String code) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		// 实例化连接配置对象
		WebApi api = new WebApi();
		// 调用中标院接口
		String[] params = new String[] { "orgLoginName", "password", "ukeyId", "orgCode", "type", "Code",
				"striPageIndex", "striPageSize" };
		String[] paramsValue = new String[] { CniswsUtil.getUserName(), CniswsUtil.getPassword(), "",
				CniswsUtil.getOrgCode(), type, code, "1", "5" };
		OMElement qs = null;
		try {
			qs = api.callMethod(CniswsUtil.getWsdl(), CniswsUtil.getNameSpace(), "getCcsOrIcsStandard", params,
					paramsValue);
		} catch (AxisFault e) {
			e.printStackTrace();
			message.setMessage("链接失败，请重试！");
			return message;
		}
		List<Map<String, Object>> list = api.getNodeList(qs);
		List<Map<String, Object>> listNew = new ArrayList<Map<String, Object>>();
		if (list.size() > 0 && list.get(0) != null) {
			for (Map<String, Object> standardWrap : list) {
				Map<String, Object> standardWrapNew = new HashMap<String, Object>();
				listNew.add(standardWrapNew);
				standardWrapNew.put("recordState", standardWrap.get("a000"));
				standardWrapNew.put("recordStateInt", standardWrap.get("a001"));
				standardWrapNew.put("standardNo", standardWrap.get("a100"));
				standardWrapNew.put("standardName", standardWrap.get("a298"));
				standardWrapNew.put("standardEngName", standardWrap.get("a302"));
			}
			message.setObject(listNew);
			message.setMessage("查询成功！");
			message.setSuccess(Boolean.TRUE);
		} else {
			message.setMessage("获取失败");
		}
		return message;
	}

	/**
	 * @Description 在线预览标准的电子全文前3页信息，预览页数默认值为3，后台可根据需要设置预览页数。
	 * @author yinyg
	 * @param userName
	 *            用户名
	 * @param code
	 *            A100文献号
	 * @param filename
	 *            文件名
	 * @return
	 */
	@Override
	public Message getElecFileByBefore(String code, String filename) {
		Message message = new Message();
		WebApi api = new WebApi();
		OMElement ome = null;
		String[] params = new String[] { "orgLoginName", "password", "ukeyId", "orgCode", "userLoginName", "A100",
				"filename" };
		String[] paramsValue = new String[] { CniswsUtil.getUserName(), CniswsUtil.getPassword(), "", "", "", code,
				filename };
		try {
			ome = api.callMethod(CniswsUtil.getWsdl(), CniswsUtil.getNameSpace(), "getElecFileByBefore", params,
					paramsValue);
		} catch (AxisFault e) {
			e.printStackTrace();
		}
		if (ome != null) {
			String output = null;
			String test123 = ome.toString();
			output = test123.substring(test123.indexOf("<cnisws:response>"), test123.indexOf("</cnisws:response>"))
					.replace("<cnisws:response>", "");
			byte[] byteOut = Base64Kit.decode(output);
			InputStream input = new ByteArrayInputStream(byteOut);
			BufferedInputStream in = new BufferedInputStream(input);
			String pdfPath = SystemConfiguration.getMap().get("filePath");
			if (!new File(pdfPath).exists()) {
				new File(pdfPath).mkdirs();
			}
			String filePath = pdfPath + File.separator + filename;
			File file = new File(filePath);
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			OutputStream out = null;
			try {
				out = new FileOutputStream(filePath);
				IOUtils.copy(in, out);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (out != null) {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			IOUtils.closeQuietly(in);
			api.readPDF(file.getPath());
			System.out.println();
			message.setObject(file.getPath().replace(pdfPath, "/upload/"));
		}
		return message;
	}

	/**
	 * @Description 根据标识符（A001）获得标准列表页或详情页中题录的电子全文信息，一条题录可能对应多个电子全文；
	 *              对于下订单购买的用户传入用户登录名（userLoginName），可以返回用户是否已购买（isBuy）信息。
	 * @author yinyg
	 * @param userName
	 *            用户名
	 * @param code
	 *            A001标识符
	 * @return
	 */
	@Override
	public Message getStandardElec(String userName, String code) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		WebApi a = new WebApi();
		OMElement ome = null;
		String[] params = new String[] { "orgLoginName", "password", "ukeyId", "orgCode", "userLoginName", "A001" };
		String[] paramsValue = new String[] { CniswsUtil.getUserName(), CniswsUtil.getPassword(), "",
				CniswsUtil.getOrgCode(), userName, code };
		try {
			ome = a.callMethod(CniswsUtil.getWsdl(), CniswsUtil.getNameSpace(), "getStandardElec", params, paramsValue);
		} catch (AxisFault e) {
			e.printStackTrace();
		}
		if (ome != null) {
			List<Map<String, Object>> list = a.getNodeList(ome);
			if (list != null && list.size() > 0) {
				message.setObject(list);
				message.setMessage("查询成功！");
				message.setSuccess(Boolean.TRUE);
			} else {
				message.setMessage("没有获得当前标准号相关信息！");
			}
			System.out.println(list);
		}
		return message;
	}

	/**
	 * @Description 检查该用户是否收藏该标准
	 * @author yinyg
	 * @param userName
	 *            用户名
	 * @param code
	 *            编号
	 * @return
	 */
	@Override
	public Message checkCollection(String userName, String code) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		Integer id = UserInfo.dao.getLocalUserId(userName);
		String sql = Db.getSql("specisSql.checkCollection");
		Record record = Db.findFirst(sql, id, code);
		if (record != null) {
			message.setSuccess(true);
		}
		return message;
	}

	/**
	 * @Description 检查该用户是否跟踪该标准
	 * @author yinyg
	 * @param userName
	 *            用户名
	 * @param code
	 *            编号
	 * @return
	 */
	@Override
	public Message checkTracking(String userName, String code) {
		Message message = new Message();
		message.setSuccess(Boolean.FALSE);
		Integer id = UserInfo.dao.getLocalUserId(userName);
		String sql = Db.getSql("specisSql.checkTracking");
		Record record = Db.findFirst(sql, id, code);
		if (record != null) {
			message.setSuccess(true);
		}
		return message;
	}

}
